// @/api/contractApi.js
import request from '@/api/request';

const contractApi = {
  // ================== 合同模板管理 ==================
  /**
   * 获取合同模板列表（支持分页、搜索、分类筛选等）
   * GET /api/contracts?page=0&size=10&keyword=&category=
   */
  getTemplates: (params) => {
    return request({
      url: '/api/contracts',
      method: 'get',
      params
    });
  },

  /**
   * 获取单个合同详情
   * GET /api/contracts/{id}
   */
  getTemplateDetail: (id) => {
    return request({
      url: `/api/contracts/${id}`,
      method: 'get'
    });
  },

  /**
   * 创建新合同模板（仅基本信息）
   * POST /api/contracts { name, category, description }
   */
  createContract: (data) => {
    return request({
      url: '/api/contracts',
      method: 'post',
      data
    });
  },

  /**
   * 更新合同模板（仅基本信息）
   * PUT /api/contracts/{id}
   */
  updateContract: (id, data) => {
    return request({
      url: `/api/contracts/${id}`,
      method: 'put',
      data
    });
  },

  /**
   * 删除合同模板
   * DELETE /api/contracts/{id}
   */
  deleteContract: (id) => {
    return request({
      url: `/api/contracts/${id}`,
      method: 'delete'
    });
  },

  // ================== 文件上传与处理 ==================
  /**
   * 上传单个文件（返回 fileId）
   * POST /api/contracts/upload-file (multipart/form-data)
   */
  uploadSingleFile: (file) => {
    const formData = new FormData();
    formData.append('file', file);
    return request({
      url: '/api/contracts/upload-file',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },

  /**
   * 创建合同 + 文件上传（组合操作）
   */
  createContractWithFile: async (contractData, file) => {
    try {
      console.log('开始创建合同并上传文件:', file.name);

      // 1. 上传文件获取 fileId
      const uploadResponse = await contractApi.uploadSingleFile(file);
      const fileId = uploadResponse.data?.fileId || uploadResponse.fileId;
      if (!fileId) {
        throw new Error('文件上传失败：响应中缺少 fileId');
      }

      // 2. 创建合同记录
      const contractResponse = await contractApi.createContract({
        ...contractData,
        fileId,
        fileName: file.name
      });

      // 3. 触发预览图生成（可选，用于首次预览加速）
      try {
        await contractApi.previewImage(contractResponse.data?.id || contractResponse.id);
      } catch (err) {
        console.warn(`预览图生成未完成，将在首次预览时触发`, err);
      }

      // 返回增强版数据（含预览图URL）
      const contractId = contractResponse.data?.id || contractResponse.id;
      return {
        ...contractResponse,
        imgUrl: `http://localhost:8088/api/contracts/${contractId}/preview?t=${Date.now()}`
      };
    } catch (error) {
      console.error('创建合同并上传文件失败:', error);
      throw error;
    }
  },

  /**
   * 更新合同 + 可选文件上传
   */
  updateContractWithFile: async (id, contractData, file) => {
    try {
      let updatedFileId = contractData.fileId;

      if (file) {
        const uploadResponse = await contractApi.uploadSingleFile(file);
        updatedFileId = uploadResponse.data?.fileId || uploadResponse.fileId;
        if (!updatedFileId) {
          throw new Error('文件上传失败：无法获取新的 fileId');
        }
      }

      // 构造包含所有合同信息的数据对象
      const fullContractData = {
        ...contractData,
        fileId: updatedFileId,
        fileName: file?.name || contractData.fileName
      };

      // 更新合同信息
      const updatedContract = await contractApi.updateContract(id, fullContractData);

      // 如果有文件上传，触发预览图更新
      if (file) {
        try {
          await contractApi.previewImage(id);
        } catch (err) {
          console.warn(`预览图更新失败`, err);
        }

        // 返回包含预览图URL的合同信息
        return {
          ...updatedContract,
          imgUrl: `http://localhost:8088/api/contracts/${id}/preview?t=${Date.now()}`
        };
      }

      return updatedContract;
    } catch (error) {
      console.error('更新合同并上传文件失败:', error);
      throw error;
    }
  },

  // ================== 预览与下载 ==================
  /**
   * 预览合同（PDF转图片）
   * GET /api/contracts/{id}/preview → 返回图片 blob
   */
  previewImage: (id) => {
    return request({
      url: `/api/contracts/${id}/preview`,
      method: 'get',
      responseType: 'blob'
    }).then(response => {
      if (!response.data) return '';
      return URL.createObjectURL(response.data);
    }).catch(error => {
      console.error('预览图片请求失败:', error);
      return '';
    });
  },

  /**
   * 下载合同 PDF 文件
   * GET /api/contracts/{id}/download → 返回二进制流
   */
  downloadFile: (id) => {
    return request({
      url: `/api/contracts/${id}/download`,
      method: 'get',
      responseType: 'blob' // 处理二进制 PDF
    });
  },

  /**
   * 记录下载次数（+1）
   * POST /api/contracts/{id}/downloadCount
   */
  recordDownload: (id) => {
    return request({
      url: `/api/contracts/${id}/downloadCount`,
      method: 'post'
    });
  },

  /**
   * 记录预览次数（+1）
   * POST /api/contracts/{id}/previewCount
   */
  recordPreview: (id) => {
    return request({
      url: `/api/contracts/${id}/previewCount`,
      method: 'post'
    });
  },

  // ================== 收藏功能 ==================
  /**
   * 切换收藏状态
   * POST /api/contracts/{id}/favorite { "favorite": true/false }
   */
  toggleFavorite: (id, favorite) => {
    return request({
      url: `/api/contracts/${id}/favorite`,
      method: 'post',
      data: { favorite }
    });
  },

  /**
   * 获取当前用户的收藏合同列表
   * GET /api/contracts/favorites
   */
  getUserFavorites: (params) => {
    console.log('调用获取收藏列表API，参数:', params);
    return request({
      url: '/api/contracts/favorites',
      method: 'get',
      params: params || {}
    });
  },

  // ================== 其他辅助接口 ==================
  /**
   * 获取所有合同分类
   * GET /api/contracts/categories
   */
  getAllCategories: () => {
    return request({
      url: '/api/contracts/categories',
      method: 'get'
    });
  },

  /**
   * 获取统计信息（总数、总下载、总预览等）
   * GET /api/contracts/stats
   */
  getContractStats: () => {
    return request({
      url: '/api/contracts/stats',
      method: 'get'
    });
  }
};

export default contractApi;